<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="auction_title" label="采购单">
        <uni-easyinput placeholder="采购单标题" v-model="formData.auction_title" :disabled="true"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="auction_serial_number" label="采购单编号">
        <uni-easyinput placeholder="采购单编号" v-model="formData.auction_serial_number" :disabled="true"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="supplier_user_name" label="供应商">
        <uni-easyinput placeholder="供应商名称" v-model="formData.supplier_user_name" :disabled="true"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="amount" label="报价金额">
        <uni-easyinput type="digit" placeholder="请输入报价金额" v-model="formData.amount"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="timestamp" label="报价时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.timestamp" :disabled="true"></uni-datetime-picker>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <button class="uni-button" style="width: 100px; margin-left: 15px;" @click="navigateBack">返回</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/bids.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'bids';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "auction_id": "",
        "auction_title": "",
        "auction_serial_number": "",
        "supplier_user_id": "",
        "supplier_user_name": "",
        "amount": null,
        "timestamp": Date.now(),
        "start_price": 0 // 用于验证报价
      }
      return {
        formData,
        formOptions: {},
        rules: {
          ...getValidator(["auction_id", "supplier_user_id", "amount", "timestamp"])
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 加载采购单信息
       */
      loadAuctionInfo(auctionId) {
        db.collection('auctions').doc(auctionId).get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData.auction_id = auctionId
            this.formData.auction_title = data.title
            this.formData.auction_serial_number = data.serial_number
            this.formData.start_price = data.start_price || 0
          }
        }).catch((err) => {
          uni.showModal({
            content: '加载采购单信息失败: ' + err.message,
            showCancel: false
          })
        })
      },
      
      /**
       * 获取当前用户信息
       */
      getCurrentUserInfo() {
        // 获取当前用户ID（实际项目中需要根据uni-id的实现方式获取）
        const userId = uni.getStorageSync('uni_id')
        if (userId) {
          this.formData.supplier_user_id = userId
          // 获取用户名称信息
          db.collection('uni-id-users').doc(userId).get().then((res) => {
            const userData = res.result.data[0]
            if (userData) {
              this.formData.supplier_user_name = userData.nickname || userData.username || userId
            }
          }).catch((err) => {
            console.error('获取用户信息失败:', err)
            this.formData.supplier_user_name = userId
          })
        }
      },
      
      /**
       * 返回上一页
       */
      navigateBack() {
        uni.navigateBack()
      },
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        // 验证报价金额是否低于起始价格
        if (this.formData.amount && this.formData.start_price && this.formData.amount >= this.formData.start_price) {
          uni.showModal({
            content: '报价金额必须低于起始价格',
            showCancel: false
          })
          uni.hideLoading()
          return
        }
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 只提交数据库需要的字段
        const submitData = {
          auction_id: value.auction_id,
          supplier_user_id: value.supplier_user_id,
          amount: value.amount,
          timestamp: value.timestamp
        }
        
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(submitData).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
